<template>
  <div class="contianer-app" ref="containerRef">
    <div style="height: 100%; display: flex; flex-direction: column; max-width: 800px; margin: 0px auto">
      <div ref="scrollRef" class="box">
        <div v-for="(item, index) in chatList">
          <Message :text="item.text" :isloading="item.isloading" style="margin-top: 20px" :uuid="index" :isQuention="item.isQuention"></Message>
        </div>

        <div style="margin-top: 20px; display: flex; justify-content: center" v-if="loading">
          <el-button @click="handleStop">停止对话</el-button>
        </div>
      </div>
      <div class="bottom-container">
        <el-card style="width: 100%; padding: 0; height: 100%">
          <el-input v-model="textarea" maxlength="200" placeholder="你可以问我" type="textarea" autosize @keypress="handleEnter" />
          <div style="margin-top: 10px; display: flex; justify-content: flex-end; align-items: center">
            <div style="margin-right: 10px">{{ textarea.length }}/200</div>
            <el-button @click="getStream(textarea)">发送</el-button>
            <!-- <el-button @click="generateScreenshots">生成截图</el-button> -->
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import Message from '@/components/Message.vue'
import html2canvas from 'html2canvas'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { storeToRefs } from 'pinia'
import { useLoadingStore } from './store/index'
const { loading } = storeToRefs(useLoadingStore())
const { setLoading } = useLoadingStore()
const chatList = ref([])
const textarea = ref('')
onMounted(() => {})

const scrollRef = ref()
let controller = new AbortController()

const scrollToBottom = async () => {
  await nextTick()
  if (scrollRef.value) scrollRef.value.scrollTop = scrollRef.value.scrollHeight
}
const screenUrl = ref('')
const containerRef = ref()

function handleEnter(event) {
  // console.log(event)
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    getStream(textarea.value)
  }
}

async function generateScreenshots() {
  await nextTick()
  const imgDom = containerRef.value
  const canvas = document.createElement('canvas')
  const width = parseInt(window.getComputedStyle(imgDom).width)
  const height = parseInt(window.getComputedStyle(imgDom).height)
  let scale = getPixelRatio()
  canvas.width = width * scale
  canvas.height = height * scale
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  html2canvas(imgDom, {
    canvas: canvas,
    scale: scale,
    useCORS: true, // 开启跨域设置，需要后台设置cors
  }).then((canvas) => {
    // toDataURL函数生成img标签的可用数据  图片格式转成 base64
    let dataURL = canvas.toDataURL('image/png')
    screenUrl.value = dataURL
  })

  function getPixelRatio() {
    if (window.devicePixelRatio && window.devicePixelRatio > 1) {
      return window.devicePixelRatio
    }
    return 1
  }
}

function getStream(conent) {
  if (loading.value) {
    return
  }
  if (!conent || conent.trim() === '') return
  let str = ''
  controller = new AbortController()
  setLoading(true)

  chatList.value.push({
    text: conent,
    isloading: false,
    isQuention: true,
  })
  scrollToBottom()

  chatList.value.push({
    text: '',
    isloading: true,
  })

  //彪哥服务器写法
  // const formData = new FormData()
  // formData.append('content', textarea.value)
  // fetchEventSource('http://10.8.0.6:8051/chat/chatdoc', {
  //   method: 'post',
  //   headers: {
  //     // 'Content-Type': 'application/json',
  //     Authorization:
  //       'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MSwicm9sZSI6InJvb3QiLCJleHAiOjE3MDEyMzY1NDksImlzcyI6ImdhdGV3YXlBcHAifQ.mO4ZsuxwXvLTmki5gKCfBzG5UxBzQ0GnmwIP9ZErpxw',
  //   },
  //   body: formData,
  //   openWhenHidden: true,
  //   signal: controller.signal,
  //   onclose() {
  //     console.log('close')
  //   },
  //   onerror(err) {
  //     console.log(err, 'err')
  //   },
  //   onmessage(res) {

  //     const tranformData = JSON.parse(res.data)
  //     if (tranformData.status === 1 || tranformData.status === 2) {
  //       const tmpstr = tranformData?.content
  //       str += tmpstr
  //       const index = chatList.value.length - 1
  //       chatList.value[index].text = str
  //       if (tranformData.status === 2) {
  //         setLoading(false)
  //         chatList.value[index].isloading = false
  //       }
  //     }

  //   },
  // })

  // 本地服务器写法
  fetchEventSource('http://192.168.1.194:3000/xunfei', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      text: conent,
    }),
    openWhenHidden: true,
    signal: controller.signal,
    onmessage(res) {
      const tranformData = JSON.parse(res.data)
      const tmpstr = tranformData?.payload?.choices?.text[0].content
      str += tmpstr
      const index = chatList.value.length - 1
      chatList.value[index].text = str
      scrollRef.value.scrollTop = scrollRef.value.height
      if (tranformData.header.status == 2) {
        setLoading(false)
        chatList.value[index].isloading = false
      }
      scrollToBottom()
    },
  })
}

function handleStop() {
  if (loading.value) {
    controller.abort()
    chatList.value[chatList.value.length - 1].isloading = false
    setLoading(false)
  }
}
</script>

<style scoped lang="scss">
:deep(.el-textarea__inner:focus) {
  box-shadow: none;
}
:deep(.el-textarea__inner:hover) {
  box-shadow: none;
}
:deep(.el-textarea__inner) {
  resize: none;
  box-shadow: none;
}
.contianer-app {
  height: 100vh;
  padding: 20px 0;
  overflow: hidden;
  box-sizing: border-box;
  &::-webkit-scrollbar {
    display: none;
  }
}
.box {
  flex: 1;
  height: 100%;
  background: #f4f6f8;
  width: 100%;
  padding-bottom: 20px;
  padding: 20px;
  box-sizing: border-box;

  &::-webkit-scrollbar {
    display: none;
  }
  overflow-y: auto;
}
.bottom-container {
  // position: fixed;
  position: sticky;
  max-width: 800px;
  box-sizing: border-box;
  height: 200px;
  display: flex;
  // margin: 0 auto;
  align-items: center;
  // bottom: 0;
}
</style>
